var CLODOP_VERSION_FOR_UPD = "6.2.2.6";
var LODOP_VERSION_FOR_UPD = "6.2.2.6";
var CreatedOKLodop7766 = null;
var currentLodopScriptArg = (function () {
	var tmpscripts = document.getElementsByTagName('script');
	var currentScript = tmpscripts[tmpscripts.length - 1];
	return currentScript.getAttribute('src');
})();
//====判断是否需要安装CLodop云打印服务器:====
function needCLodop() {
	//if ("undefined"!=typeof EnableLocalWeb && 1==EnableLocalWeb ){return true;}  //2020-1-20
	if (currentLodopScriptArg.indexOf("needCLodop=1") > -1) { return true; }
	try {
		var ua = navigator.userAgent;
		if (ua.match(/Windows\sPhone/i) != null) return true;
		if (ua.match(/iPhone|iPod/i) != null) return true;
		if (ua.match(/Android/i) != null) return true;
		if (ua.match(/Edge\D?\d+/i) != null) return true;

		var verTrident = ua.match(/Trident\D?\d+/i);
		var verIE = ua.match(/MSIE\D?\d+/i);
		var verOPR = ua.match(/OPR\D?\d+/i);
		var verFF = ua.match(/Firefox\D?\d+/i);
		var x64 = ua.match(/x64/i);
		if ((verTrident == null) && (verIE == null) && (x64 !== null))
			return true; else
			if (verFF !== null) {
				verFF = verFF[0].match(/\d+/);
				if ((verFF[0] >= 41) || (x64 !== null)) return true;
			} else
				if (verOPR !== null) {
					verOPR = verOPR[0].match(/\d+/);
					if (verOPR[0] >= 32) return true;
				} else
					if ((verTrident == null) && (verIE == null)) {
						var verChrome = ua.match(/Chrome\D?\d+/i);
						if (verChrome !== null) {
							verChrome = verChrome[0].match(/\d+/);
							if (verChrome[0] >= 41) return true;
						};
					};
		return false;
	} catch (err) { return true; };
};

//用双端口加载主JS文件Lodop.js(或CLodopfuncs.js兼容老版本)以防其中某端口被占:
var MainJS = "CLodopfuncs.js",
	URL_WS1 = "ws://localhost:8000/" + MainJS,                //ws用8000/18000
	URL_WS2 = "ws://localhost:18000/" + MainJS,
	URL_HTTP1 = "http://localhost:8000/" + MainJS,              //http用8000/18000
	URL_HTTP2 = "http://localhost:18000/" + MainJS,
	URL_HTTP3 = "https://localhost.lodop.net:8443/" + MainJS;   //https用8000/8443
var LoadJsState;
//==检查加载成功与否，如没成功则用http(s)再试==
//==低版本CLODOP6.561/Lodop7.043及前)用本方法==
function checkOrTryHttp() {
	if (window.getCLodop) {
		LoadJsState = "complete";
		return true;
	}
	if (LoadJsState == "loadingB" || LoadJsState == "complete") return;
	LoadJsState = "loadingB";
	var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
	var JS1 = document.createElement("script")
		, JS2 = document.createElement("script")
		, JS3 = document.createElement("script");
	JS1.src = URL_HTTP1;
	JS2.src = URL_HTTP2;
	JS3.src = URL_HTTP3;
	JS1.onload = JS2.onload = JS3.onload = JS2.onerror = JS3.onerror = function () { LoadJsState = "complete"; }
	JS1.onerror = function (e) {
		if (window.location.protocol !== 'https:')
			head.insertBefore(JS2, head.firstChild); else
			head.insertBefore(JS3, head.firstChild);
	}
	head.insertBefore(JS1, head.firstChild);
}
// 这里用 WebSocket 适合谷歌浏览器加载clodop，内网电脑无法下载SSL证书的情况。
function loadCLodop() {
	if (!needCLodop()) return;
	CLodopIsLocal = !!((URL_WS1 + URL_WS2).match(/\/\/localho|\/\/127.0.0./i));
	LoadJsState = "loadingA";
	if (!window.WebSocket && window.MozWebSocket) window.WebSocket = window.MozWebSocket;
	//ws方式速度快(小于200ms)且可避免CORS错误,但要求Lodop版本足够新:
	try {
		var WSK1 = new WebSocket(URL_WS1);
		WSK1.onopen = function (e) { setTimeout("checkOrTryHttp();", 200); }
		WSK1.onmessage = function (e) { if (!window.getCLodop) eval(e.data); }
		WSK1.onerror = function (e) {
			var WSK2 = new WebSocket(URL_WS2);
			WSK2.onopen = function (e) { setTimeout("checkOrTryHttp();", 200); }
			WSK2.onmessage = function (e) { if (!window.getCLodop) eval(e.data); }
			WSK2.onerror = function (e) { checkOrTryHttp(); }
		}
	} catch (e) {
		// checkOrTryHttp();
		// ie强制用clodop，new WebSocket报错，只能用https的了，内网只能手工去安装lodop证书，或者连接外网一次。
		loadCLodopByHTTPS();		
	}
}

var CreatedOKLodopObject, CLodopIsLocal, CLodopJsState;
//加载CLodop时用双端口(http是8000/18000,而https是8443/8444)以防其中某端口被占,
//主JS文件“CLodopfuncs.js”是固定文件名，其内容是动态的，与当前打印环境有关:
function loadCLodopByHTTPS() {
    if (CLodopJsState == "loading" || CLodopJsState == "complete") return;
    CLodopJsState = "loading";
    var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
    var JS1 = document.createElement("script");
    var JS2 = document.createElement("script");

    if (window.location.protocol=='https:') {
      JS1.src = "https://localhost.lodop.net:8443/CLodopfuncs.js";
      JS2.src = "https://localhost.lodop.net:8444/CLodopfuncs.js";
    } else {
      JS1.src = "http://localhost:8000/CLodopfuncs.js";
      JS2.src = "http://localhost:18000/CLodopfuncs.js";
    }
    JS1.onload  = JS2.onload  = function()    {CLodopJsState = "complete";}
    JS1.onerror = JS2.onerror = function(evt) {CLodopJsState = "complete";}
    head.insertBefore(JS1, head.firstChild);
    head.insertBefore(JS2, head.firstChild);
    CLodopIsLocal = !!((JS1.src + JS2.src).match(/\/\/localho|\/\/127.0.0./i));
}

//====页面引用CLodop云打印必须的JS文件：====
if (needCLodop()) {
	var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
	var oscript = null;
	if (location.href.slice(0, 5).toLowerCase() == 'https' && typeof cefbound === "undefined") {
		//非医为浏览器
		loadCLodop();
	} else {
		oscript = document.createElement("script");
		oscript.src = "http://localhost:8000/CLodopfuncs.js?priority=1";
		head.insertBefore(oscript, head.firstChild);

		//引用双端口(8000和18000）避免其中某个被占用：
		oscript = document.createElement("script");
		oscript.src = "http://localhost:18000/CLodopfuncs.js?priority=0";
		head.insertBefore(oscript, head.firstChild);
	}
};
var websys_getMenuWin = function () {
	var win = window;
	try {
		var win = top.frames['eprmenu'];
		if (win) {
			frm = win.document.forms['fEPRMENU'];
			if (frm) return win;
		}
		win = parent.frames[0];
		if (win) {
			frm = win.document.forms["fEPRMENU"];
			if (frm) return win;
		}
		if (top) {
			frm = top.document.forms["fEPRMENU"];
			if (frm) return top;
		}
		// opener位置放到后面,如果是从portal转到his的界面,opener就跨域了
		//在新窗口打开的界面
		win = opener;
		if (win) {
			frm = win.document.forms['fEPRMENU'];
			if (frm) return win;
		}
		//在新窗口打开的界面,且包含多个iframe
		win = top.opener;
		if (win) {
			frm = win.document.forms['fEPRMENU'];
			if (frm) return win;
		}
		//main界面open开新界面中调用,8.0+
		win = top.opener;
		if (win) {
			frm = win.top.document.forms['fEPRMENU'];
			if (frm) return win.top;
		}
		win = dialogArguments;
		if (win) {
			frm = win.top.document.forms['fEPRMENU'];
			if (frm) return win.top;
		}
		win = dialogArguments.opener;
		if (win) {
			frm = win.top.document.forms['fEPRMENU'];
			if (frm) return win.top;
		}
		win = dialogArguments.window;
		if (win) {
			frm = win.top.document.forms['fEPRMENU'];
			if (frm) return win.top;
		}
		win = dialogArguments.window.opener;
		if (win) {
			frm = win.top.document.forms['fEPRMENU'];
			if (frm) return win.top;
		}
		return window;
	} catch (e) { win = window; }
	return win;
}
//====获取LODOP对象的主过程：====
function getLodop(oOBJECT, oEMBED) {
	var path = "../addins/server/";
	var strHtmFireFox = "<br><br><font color='#FF00FF'>（注意：如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它）</font>";
	var strHtmChrome = "<br><br><font color='#FF00FF'>(如果此前正常，仅因浏览器升级或重安装而出问题，需重新执行以上安装）</font>";
	//var strCLodopInstall="<br><font color='#FF00FF'>CLodop云打印服务(localhost本地)未安装启动!点击这里<a href='"+path+"lodop/CLodop_Setup_for_Win32NT.exe' target='_self'>执行安装</a>,安装后请刷新页面。</font>";
	//var strCLodopUpdate="<br><font color='#FF00FF'>CLodop云打印服务需升级!点击这里<a href='"+path+"lodop/CLodop_Setup_for_Win32NT.exe' target='_self'>执行升级</a>,升级后请刷新页面。</font>";
	var menuWin = websys_getMenuWin();
	try { CreatedOKLodop7766 = menuWin.CreatedOKLodop7766 || null; } catch (e) { CreatedOKLodop7766 = null; }
	var LODOP;
	try {
		var isIE = (navigator.userAgent.indexOf('MSIE') >= 0) || (navigator.userAgent.indexOf('Trident') >= 0);
		if (needCLodop()) {
			try { LODOP = getCLodop(); } catch (err) { if(menuWin) LODOP = menuWin.CLODOP };
			if (!LODOP && document.readyState !== "complete") { alert("C-Lodop没准备好，请稍后再试！"); return; };
			if (!LODOP) {
				if (isWin64()) {
					openLodopWindow(4, "install");
				} else {
					openLodopWindow(3, "install");
				}
				return;
			} else if (LODOP.VERSION < CLODOP_VERSION_FOR_UPD) {
				console.log("clodop 会提示升级，当前版本号：" + LODOP.VERSION);
				if (isWin64()) {
					openLodopWindow(4, "upd");
				} else {
					openLodopWindow(3, "upd");
				}
			}

			if (oEMBED && oEMBED.parentNode) oEMBED.parentNode.removeChild(oEMBED);
			if (oOBJECT && oOBJECT.parentNode) oOBJECT.parentNode.removeChild(oOBJECT);
		} else {
			//=====如果页面有Lodop就直接使用，没有则新建:==========
			if (oOBJECT != undefined || oEMBED != undefined) {
				if (isIE) LODOP = oOBJECT; else LODOP = oEMBED;
			} else if (CreatedOKLodop7766 == null) {
				LODOP = menuWin.document.createElement("object");
				LODOP.setAttribute("width", 0);
				LODOP.setAttribute("height", 0);
				LODOP.setAttribute("style", "position:absolute;left:0px;top:-100px;width:0px;height:0px;");
				if (isIE) LODOP.setAttribute("classid", "clsid:2105C259-1E0C-4534-8141-A753534CB4CA");
				else LODOP.setAttribute("type", "application/x-print-lodop");
				menuWin.document.documentElement.appendChild(LODOP);
				CreatedOKLodop7766 = LODOP;
				menuWin.CreatedOKLodop7766 = LODOP;
			} else {
				LODOP = CreatedOKLodop7766;
			}
			//=====Lodop插件未安装时提示下载地址:==========
			if ((LODOP == null) || (typeof (LODOP.VERSION) == "undefined")) {
				menuWin.CreatedOKLodop7766 = null;
				CreatedOKLodop7766 = null;
				if (navigator.userAgent.indexOf('Chrome') >= 0)
					document.body.innerHTML = strHtmChrome + document.body.innerHTML;
				if (navigator.userAgent.indexOf('Firefox') >= 0)
					document.body.innerHTML = strHtmFireFox + document.body.innerHTML;
				if (isWin64()) {
					openLodopWindow(2, "install");
				} else {
					openLodopWindow(1, "install");
				}
				return;
			} else if (LODOP.VERSION < LODOP_VERSION_FOR_UPD) {
				console.log("lodop 会提示升级，当前版本号：" + LODOP.VERSION);
				if (isWin64()) {
					openLodopWindow(2, "upd");
				} else {
					openLodopWindow(1, "upd");
				}
			}
		};
		//===如下空白位置适合调用统一功能(如注册语句、语言选择等):===
		LODOP.SET_LICENSES('\u4E1C\u534E\u533B\u4E3A\u79D1\u6280\u6709\u9650\u516C\u53F8', "4EF6E3D5AB0D478F5A07D05CDDDE2365", "\u6771\u83EF\u91AB\u70BA\u79D1\u6280\u6709\u9650\u516C\u53F8", "7C4A2B70D17D01CCD5CB2A3A6B4D3200");
		LODOP.SET_LICENSES("THIRD LICENSE", "", "DHC Medical Science & Technology Co., Ltd.", "604523CF08513643CB90BACED8EFF303");
		//===========================================================
		return LODOP;
	} catch (err) { alert("getLodop出错:" + err.message); };
};

var baseUrl = '..';
if (location.href.indexOf('/web/') > -1) baseUrl = location.href.split('/web/')[0] + '/web/csp/dhctt.lodopDownload.csp';
var showModalFlag = false; 
/* 20230207 remove the dependent of websys.js(has error) huangzhi
if ("undefined" != typeof $) {
	if ($.extend && $.fn.window && "undefined" != typeof websys_showModal) {
		showModalFlag = true;
	}
}*/
function openLodopWindow(type, actionType) {
	// ?type=1&actionType=install
	if (showModalFlag) {
		websys_showModal({
			url: baseUrl + "?type=" + type + "&actionType=" + actionType,
			title: 'Lodop',
			width: 300,
			height: 150
		});
	} else {
		window.open(baseUrl + "?type=" + type + "&actionType=" + actionType, "lodopUp", 'top=100,left=300,width=300,height=150,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=no,maximized=yes');
	}
}
function isWin64() {
	var agent = navigator.userAgent.toLowerCase();
	if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) {
		return true;
	}
	return false;
}
